from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

def cut(filename, savefile, row, col):
    img = Image.open(filename)
    width, height = img.size
    w = width // col
    h = height // row
    threshold = 60

    cnt = 0
    rec = []
    for r in range(row):

        for c in range(col):
            box = (c * w, r * h, (c + 1) * w, (r + 1) * h)
            timg = img.crop(box).convert('L')
            timg = timg.resize((28, 28))
            table = []
            for i in range(256):
                if i < threshold:
                    table.append(i)
                else:
                    table.append(0)

            photo = list(timg.point(table, '1').getdata())
            photo.insert(0, r)
            print(photo)
            timg.point(table, '1').save(str(cnt) + ".jpg")
            np.set_printoptions(threshold=np.inf)
            table = np.reshape(np.array(photo), (1, 785))
            rec.append(table)
            cnt += 1
    file = open(savefile + "2" + ".csv", 'w')
    # 遍历矩阵，将numpy读出
    for item in rec:
        for iitem in item:
            file.write(','.join(str(i) for i in iitem))  # numpyInt64->int->str
        file.write("\n")
    file.close()

if __name__ == "__main__":
    #cut("./img/test1.jpg", "./Data/mytestData", 10, 4)
    cut("./img/1.png", "./Data/mytestData", 1, 5)